package dnl.dtools.grm.operations.io;

import de.schlichtherle.io.File;
import dnl.dtools.grm.LocalFileSystemEntry;
import dnl.dtools.grm.Resource;
import dnl.dtools.grm.operations.ResourceOperationException;
import dnl.dtools.grm.operations.TargetBasedResourceOperation;
import dnl.logging.LightLog;

/**
 * 
 * @author daniel
 */
public class LocalFsCopyOperation extends TargetBasedResourceOperation {

	public LocalFsCopyOperation(Resource[] sources, Resource target) {
		super(sources, target);
	}

	public int getProgress() {
		return 0;
	}

	@Override
	public void operate() throws ResourceOperationException {
		LocalFileSystemEntry r2 = (LocalFileSystemEntry) target;
		
		for (int i = 0; i < sources.length; i++) {
			LocalFileSystemEntry r1 = (LocalFileSystemEntry) sources[i];
			boolean success = true;
			// Using getChild() misbehaves ... lets concatenate some Strings
			File newf = new File(r2.getFile().getDelegate().getAbsolutePath()+File.separator+r1.getName());
			if(r1.isDirectory()){
				success = r1.getFile().copyAllTo(newf);
			}
			else {
				if(r1.isArchive()){
					success = r1.getFile().copyAllTo(newf);
				}
				else {
					success = r1.getFile().copyTo(newf);
				}
			}
			
			StringBuffer sb = new StringBuffer();
			sb.append(success ? "Success" : "Failure");
			sb.append(" copying from "+r1+"  to  "+r2);
			LightLog.debug(sb.toString());
			
			double d = (i+1)/sources.length;
			setProgress(d);
		}
		
		finished();
	}

}
